package com.heima.homeservicemanagementsystem.controller;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.SaSessionCustomUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.heima.homeservicemanagementsystem.config.annotation.RestControllerMapping;
import com.heima.homeservicemanagementsystem.entity.SysUser;
import com.heima.homeservicemanagementsystem.module.Result;
import com.heima.homeservicemanagementsystem.service.SysUserService;
import com.heima.homeservicemanagementsystem.utils.PasswordUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.dev33.satoken.SaManager.log;

/**
 * @Description
 * @Author susu
 * @Date 2024/11/27
 */
@Tag(name = "当前登录用户")
@RestControllerMapping("currentUser")
public class CurrentuserController {
    @Resource
    private SysUserService userService;

    @GetMapping("info")
    @Operation(summary = "获取当前登录用户信息")
    public Result<SysUser> info() {
        String loginIdAsString = StpUtil.getLoginIdAsString();
//        return Result.success(userService.getById(loginIdAsString)); //不让他出现密码
        SysUser user = userService.getById(loginIdAsString);
        user.setPassword(null);
        user.setSlat(null);
        return Result.success(user);
    }

    @PutMapping("/uploadinfo")
    @Operation(summary = "在后台中更新用户的信息")
    public Result uploadinfo(@RequestBody SysUser sysuser) {
        log.info("用户信息：{}", sysuser);
        boolean b = userService.updateById(sysuser);
        if (b) {
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }

    @GetMapping("menuList")
    @Operation(summary = "用户菜单列表")
    public Result<List<JSONObject>> menuList() {
        SaSession Session = StpUtil.getSession();
        Session.clear();
        SaSession saSession = StpUtil.getSessionByLoginId(StpUtil.getLoginId());
        List<JSONObject> list = saSession.get("menu", () -> userService.listmenu());
        return Result.success(list);
    }

    @GetMapping("clearCache")
    @Operation(summary = "清除缓存")
    public Result<Boolean> clearCache() {
        SaSession Session = StpUtil.getSession();
        Session.clear();
        return Result.success(true);
    }

    //    @GetMapping("getParams")
//    @Operation(summary = "获取当前用户的角色列表和权限列表")
//    public Result<Map<String, Object>> getParams() {
////
//        Map<String, Object> map = new HashMap<>(2);
//        List<String> Roles = StpUtil.getSession().get("Role_List", () -> userService.listRoleByUserId(StpUtil.getLoginIdAsString()));
//        List<String> perms = new ArrayList<>();
//        for (String roleCode : Roles) {
//            SaSession session = SaSessionCustomUtil.getSessionById("role-" + roleCode);
//            List<String> list = session.get("Permission_List", () -> userService.listPermssionByRoleCode(roleCode));
//            perms.addAll(list);
//        }
//        map.put("roles", Roles);
//        map.put("perms", perms);
//        return Result.success(map);
//    }
    @GetMapping("getParams")
    @Operation(summary = "satoken获取当前用户的角色列表和权限列表")
    public Result<Map<String, Object>> getParams() {
//
        Map<String, Object> map = new HashMap<>(2);
        List<String> Roles = StpUtil.getSession().get("Role_List", () -> userService.listRoleByUserId(StpUtil.getLoginIdAsString()));
        List<String> perms = new ArrayList<>();
        for (String roleCode : Roles) {
            SaSession session = SaSessionCustomUtil.getSessionById("role-" + roleCode);
            List<String> list = session.get("Permission_List", () -> userService.listPermssionByRoleCode(roleCode));
            perms.addAll(list);
        }
//        List<String> uniquePermsList = perms.stream()
//                .distinct()
//                .collect(Collectors.toList());
        map.put("roles", Roles);
        map.put("perms", perms);

        return Result.success(map);
    }

    @GetMapping("getXtRole")
    @Operation(summary = "自己获取当前用户的角色列表和权限列表")
    public Result getXtRole() {
//        给后端使用
        List<String> Roles = StpUtil.getSession().get("Role_List", () -> userService.listRoleByUserId(StpUtil.getLoginIdAsString()));
        List<String> perms = new ArrayList<>();
        for (String roleCode : Roles) {
            SaSession session = SaSessionCustomUtil.getSessionById("role-" + roleCode);
            List<String> list = session.get("Permission_List", () -> userService.listPermssionByRoleCode(roleCode));
            perms.addAll(list);
        }
//        前端的
        SaSession saSession = StpUtil.getSessionByLoginId(StpUtil.getLoginId());
        List<JSONObject> roleList = saSession.get("Roles", () -> userService.getuserRoles());


        return Result.success(roleList);
    }

    //    修改用户信息
    @PostMapping("updataUser")
    public Result<Boolean> updataUser(@RequestBody SysUser user) {
        user.setId(StpUtil.getLoginIdAsString());
        if (StrUtil.isNotBlank(user.getPassword())) {
            String s = RandomUtil.randomString(16);
            user.setSlat(s);
            String password = PasswordUtils.encrypt(s, user.getPassword());
            user.setPassword(password);

        }
        if (userService.updateById(user)) {
            return Result.success();

        }
        return Result.error();
    }
}
